package com.huilian.tool.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @authou 少凡
 * @Date 2019-04-22 10:29
 */
@Slf4j
public class DownLoadFileUtil {

    /**
     * 链接url下载图片
     */
    public static void downloadFile(String imgUrl, String savePath) {
        URL url = null;
        int imageNumber = 0;
        try {
            url = new URL(imgUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            byte[] context = output.toByteArray();
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    // 判断文件是否存在
    public static boolean fileExists(File file) {

        if (file.exists()) {
            log.info("file exists");
            return true;
        } else {
            log.error("file not exists, create it ...");
            return false;
        }
    }
}
